package com.mojo.concurrent.concurrent_04_cas_atomic;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * cas示例,cas在unsafe类中大量使用，Atomic*原子类底层又调用unsafe的方法；
 * Atomic*类中通过调用unsafe类方法和volatile来进行数据修改
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/18 14:10
 */
public class CasDemo1 {
    static AtomicInteger n = new AtomicInteger(0);
    static Integer m = 0;
    //不能使用unsafe
    // private static final Unsafe unsafe = Unsafe.getUnsafe();

    public static void main(String[] args) {
        System.out.println(n);
        List<Thread> list = new ArrayList<>();
        for (int i = 0; i < 500; i++) {
            Thread t = new Thread(CasDemo1::increase);
            list.add(t);
        }
        for (Thread thread : list) {
            thread.start();
        }
        for (Thread thread : list) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("n===>" + n);
        System.out.println("m===>" + m);
        // int i = unsafe.addressSize();
    }

    private static void increase() {
        // 原子操作
        n.getAndIncrement();
        // 非原子操作
        m++;
    }

}